#include "stat_request.h"

#include <boost/lexical_cast.hpp>

#include "base/logging.h"
#include "subscriber_cache.h"
#include "uid_session_map.h"
#include "linger_session_map.h"
#include "rpc_thread_manager.h"
#include "http_service.h"
#include "comet_subscribe_request.h"
#include "comet_publish_request.h"

namespace imserver {

std::string FormatedTime(time_t t) {
  struct tm lt;
  localtime_r(&t, &lt);

  const int MAX_LEN = 24;
  char res[MAX_LEN];
  res[MAX_LEN - 1] = 0;
  snprintf(res, MAX_LEN - 1, "%d-%02d-%02d %02d:%02d:%02d", lt.tm_year + 1900,
      lt.tm_mon + 1, lt.tm_mday, lt.tm_hour, lt.tm_min, lt.tm_sec);

  return res;
}

bool StatRequest::Response() {
  std::stringstream body;
  body << "alive_since " << FormatedTime(g_alive_since) << "\n"
       << "server_time " << FormatedTime(time(NULL)) << "\n"
       << "sessions " << UidSessionMap::Instance().size() << "\n"
       << "linger_sessions " << LingerSessionMap::Instance().size() << "\n"

       << "subscribers " << SubscriberCache::Instance().size() << "\n"
       << "subscribe_ctors " << CometSubscribeRequest::ctor_count_ << "\n"
       << "subscribe_outs " << CometSubscribeRequest::out_messages_ << "\n"

       << "publish_ctors " << CometPublishRequest::ctor_count_ << "\n"
       << "publish_200s " << CometPublishRequest::in_200_ << "\n"
       << "publish_retries " << CometPublishRequest::in_retry_ << "\n"
       << "publish_typings " << CometPublishRequest::in_typing_ << "\n"
       << "publish_400s " << CometPublishRequest::in_400_ << "\n"
       << "publish_401s " << CometPublishRequest::in_401_ << "\n"

       << "idle_workers " << GetThreadManager()->idleWorkerCount() << "\n"
       << "total_workers " << GetThreadManager()->workerCount() << "\n"
       << "pending_tasks " << GetThreadManager()->pendingTaskCount() << "\n"
       << "total_tasks " << GetThreadManager()->totalTaskCount() << "\n"
       << "max_pending_tasks " << GetThreadManager()->pendingTaskCountMax() << "\n"
       << "expired_tasks " << GetThreadManager()->expiredTaskCount() << "\n";

  response_ = "HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\nContent-Length: ";
  response_ += boost::lexical_cast<std::string>(body.str().size());
  response_.append("\r\n\r\n");

  response_.append(body.str());
  LOG_INFO("Stat Request " << url_ << " addr=" << remote_addr());
  connection_->WriteResponse(response_);
  if (query_param("debug1") == "dump_sessions") {
    UidSessionMap::Instance().Dump();
  }
  if (query_param("debug2") == "dump_subscribers") {
    SubscriberCache::Instance().Dump();
  }
  return true;
}

}

